<template>
  <div class="app-container" style="padding: 5px;">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="110px" label-position="top">
        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker v-model="queryParams.startDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @change="handleQuery"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker v-model="queryParams.endDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @change="handleQuery"></el-date-picker>
        </el-form-item>
        <el-form-item label="单据类型" prop="cls">
          <el-select v-model="queryParams.cls" filterable @change="handleQuery">
            <el-option
              v-for="item in clsList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否本周" prop="ifWk">
          <el-select v-model="queryParams.ifWk" filterable @change="handleQuery">
            <el-option
              v-for="item in ifwkList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 5px;">
      <div slot="header" class="clearfix">
        <center><span style="font-weight: bold;color: #0099ff;font-size: 16px;">{{ queryParams.startDate }}至{{ queryParams.endDate }}-{{ queryParams.cls=="all"?"全部单据类型":queryParams.cls }}-汇总</span>
        <span style="font-size: 12px;color: black;margin-left: 20px;">单位：均为最小换算单位1.例如：种子-->千粒 |  种球 --> 颗 | 种苗 --> 株 | 洋桔梗 --> 盘</span>
        </center>
      </div>
      <el-table :data="summaryList" border stripe>
        <el-table-column label="类型" align="center" prop="typeName" ></el-table-column>
        <el-table-column label="种子" align="center" prop="zz" >
          <template slot-scope="scope">
            <span v-if="scope.row.typeName=='数量'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-document-copy" style="color:blue;font-size: 20px;"></i> {{ scope.row.zz }}</span>
            <span v-if="scope.row.typeName=='金额'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-coin" style="color:gold;font-size: 20px;"></i> {{ scope.row.zz }}万元</span>
          </template>
        </el-table-column>
        <el-table-column label="种苗" align="center" prop="zm" >
          <template slot-scope="scope">
            <span v-if="scope.row.typeName=='数量'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-document-copy" style="color:blue;font-size: 20px;"></i> {{ scope.row.zm }}</span>
            <span v-if="scope.row.typeName=='金额'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-coin" style="color:gold;font-size: 20px;"></i> {{ scope.row.zm }}万元</span>
          </template>
        </el-table-column>
        <el-table-column label="种球" align="center" prop="zq" >
          <template slot-scope="scope">
            <span v-if="scope.row.typeName=='数量'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-document-copy" style="color:blue;font-size: 20px;"></i> {{ scope.row.zq }}</span>
            <span v-if="scope.row.typeName=='金额'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-coin" style="color:gold;font-size: 20px;"></i> {{ scope.row.zq }}万元</span>
          </template>
        </el-table-column>
        <el-table-column label="其他" align="center" prop="qt" >
          <template slot-scope="scope">
            <span v-if="scope.row.typeName=='数量'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-document-copy" style="color:blue;font-size: 20px;"></i> {{ scope.row.qt }}</span>
            <span v-if="scope.row.typeName=='金额'" style="font-size: 14px;font-weight: bold;"><i class="el-icon-coin" style="color:gold;font-size: 20px;"></i> {{ scope.row.qt }}万元</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card style="margin-top: 5px;">
      <div slot="header" class="clearfix">
        <center><span style="font-weight: bold;color: #0099ff;font-size: 16px;">{{ queryParams.startDate }}至{{ queryParams.endDate }}-{{ queryParams.cls=="all"?"全部单据类型":queryParams.cls }}-明细 品种：{{ queryParams.productName==null?"全部品种":queryParams.productName }}</span></center>
      </div>
      <el-table :data="cgDetailList" border stripe height="600" :span-method="rowSpanMethod">
        <el-table-column label="供应商名称" align="center" prop="vendor_name"></el-table-column>
        <el-table-column label="采购人员" align="center" prop="operator_name" width="80"></el-table-column>
        <el-table-column label="大品类" align="center" prop="bigname" width="150"></el-table-column>
        <el-table-column label="系列规格" align="center" prop="xlname" width="150"></el-table-column>
        <el-table-column label="产品名称" align="left" prop="product_name"></el-table-column>
        <el-table-column label="单据日期" align="center" prop="vdate"></el-table-column>
        <el-table-column label="订单号" align="center" prop="djcode"></el-table-column>
        <el-table-column label="订单金额(万元)" align="center" prop="orisum" width="100">
          <template slot-scope="scope">
            {{ Number(scope.row.orisum).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="qty" width="100">
          <template slot-scope="scope">
            {{ Number(scope.row.qty).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="单价(元)" align="center" prop="unit_price" width="100">
          <template slot-scope="scope">
            {{ Number(scope.row.unit_price).toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-row>
      <el-col :span="12">
        <el-card style="margin-top: 5px;">
          <div slot="header" class="clearfix">
            <center><span style="font-weight: bold;color: #0099ff;font-size: 16px;">{{ queryParams.startDate }}至{{ queryParams.endDate }}-{{ queryParams.cls=="all"?"全部单据类型":queryParams.cls }}-供应商 品种：{{ queryParams.productName==null?"全部品种":queryParams.productName }}</span></center>
          </div>
          <div ref="chart1" style="width: 100%; height: 500px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card style="margin-top: 5px;margin-left:5px;">
          <div slot="header" class="clearfix">
            <center><span style="font-weight: bold;color: #0099ff;font-size: 16px;">{{ queryParams.startDate }}至{{ queryParams.endDate }}-{{ queryParams.cls=="all"?"全部单据类型":queryParams.cls }}-品种：{{ queryParams.productName==null?"全部品种":queryParams.productName }}</span></center>
          </div>
          <div ref="chart2" style="width: 100%; height: 500px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card style="margin-top: 5px;">
      <div slot="header" class="clearfix">
        <center><span style="font-weight: bold;color: #0099ff;font-size: 16px;">{{ queryParams.startDate }}至{{ queryParams.endDate }}-{{ queryParams.cls=="all"?"全部单据类型":queryParams.cls }}-同比数据 品种：{{ queryParams.productName==null?"全部品种":queryParams.productName }}</span></center>
      </div>
      <div ref="chart3" style="width: 100%; height: 500px;"></div>
    </el-card>
  </div>
</template>

<script>
import { listCgDicts,listCgSummary,listCgDetail,listVendorSummary,listBrandsSummary,listCgMonthSummary } from "@/api/system/weekly/weeklydashboard";
import * as echarts from 'echarts';
export default {
    name: "Cgsjkb",
    data() {
        return {
          cgDetailList:[],
          summaryList: [],
          clsList: [],
          ifwkList: [],
          queryParams: {
            startDate: null,
            endDate: null,
            cls: null,
            ifWk: null,
            productName: null,
            vendorName: null,
          },
        }
    },
    created() {
      this.getCgDicts();
    },
    mounted(){

    },
    methods: {
      getCgDicts(){
        listCgDicts().then(res =>{
          this.queryParams.startDate = res.data.startDate;
          this.queryParams.endDate = res.data.endDate;
          this.clsList = res.data.cls;
          this.ifwkList = res.data.ifwk;
          this.queryParams.cls = "下定";
          this.queryParams.ifWk = "all";
          this.queryParams.productName = null;
          this.getCgSummary(); // 汇总
          this.getCgDetail();//明细
          this.getVendorSummary();//供应商
          this.getBrandSummary();// 品类
          this.getMonthSummary();//月份同比
        })
      },
      handleQuery(){
        this.getCgSummary(); // 汇总
        this.getCgDetail();//明细
        this.getVendorSummary();//供应商
        this.getBrandSummary();// 品类
        this.getMonthSummary();//月份同比
      },
      getMonthSummary(){
        listCgMonthSummary(this.queryParams).then(res =>{
          let labels = [];
          if(res.data.list.length>0){
            for(let i=0;i<res.data.list.length;i++){
              labels.push(res.data.list[i].month);
            }
          }
          const chart = echarts.init(this.$refs.chart3);
          const option = {
              tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                      type: 'shadow'
                  },
                  formatter: function (params) {
                    return params[0].data.extraInfo
                  }
              },
              legend: {},
              grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true
              },
              toolbox: {
                  feature: {
                      magicType: { show: true, type: ['line', 'bar'] },
                      restore: { show: true },
                      saveAsImage: { show: true }
                  }
              },
              xAxis: {
                  type: 'value',
                  boundaryGap: [0, 0.01]
              },
              yAxis: {
                  type: 'category',
                  data: labels,
              },
              series: [
                  {
                      type: 'bar',
                      data: res.data.list.map(item => ({
                          value: item.orisum,
                          name: item.month,
                          extraInfo: "月份："+item.month+"<br/>金额: "+item.orisum+"万<br />金额同比："+item.mrate+"%<br />数量: "+item.qty+"<br />数量同比："+item.qrate+"%"
                      })),
                      itemStyle: {
                          color: function(params) {
                              // 颜色数组
                              const colorList = res.data.colors;
                              // 根据数据索引返回对应颜色
                              return colorList[params.dataIndex % colorList.length];
                          }
                      },
                      label: {
                          show: true, // 显示标签
                          position: 'right', // 标签位置
                          formatter: '{c}万' // 标签内容格式化为数据值
                      }
                  }
              ]
          };
          chart.setOption(option);
        })
      },
      getBrandSummary(){
        listBrandsSummary(this.queryParams).then(res =>{
          let labels = [];
          if(res.data.list.length>0){
            for(let i=0;i<res.data.list.length;i++){
              labels.push(res.data.list[i].bigname);
            }
          }
          const chart = echarts.init(this.$refs.chart2);
          const option = {
              tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                      type: 'shadow'
                  },
                  formatter: function (params) {
                      return params[0].data.extraInfo
                  }
              },
              legend: {},
              grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true
              },
              toolbox: {
                  feature: {
                      magicType: { show: true, type: ['line', 'bar'] },
                      restore: { show: true },
                      saveAsImage: { show: true }
                  }
              },
              xAxis: {
                  type: 'value',
                  boundaryGap: [0, 0.01]
              },
              yAxis: {
                  type: 'category',
                  data: labels,
              },
              series: [
                  {
                      type: 'bar',
                      barWidth: 20,
                      data: res.data.list.map(item => ({
                          value: item.orisum,
                          name: item.bigname,
                          extraInfo: "品类："+item.bigname+"<br/>金额: "+item.orisum+"万<br />金额占比："+item.mrate+"%<br />数量: "+item.qty+"<br />数量占比："+item.qrate+"%"
                      })),
                      itemStyle: {
                          color: function(params) {
                              // 颜色数组
                              const colorList = res.data.colors;
                              // 根据数据索引返回对应颜色
                              return colorList[params.dataIndex % colorList.length];
                          }
                      },
                      label: {
                          show: true, // 显示标签
                          position: 'right', // 标签位置
                          formatter: '{c}万' // 标签内容格式化为数据值
                      }
                  }
              ],
              dataZoom: [
                {
                    type: 'slider', // 这里使用slider类型
                    show: true,
                    xAxisIndex: false, // 不控制x轴
                    yAxisIndex: [0], // 控制第一个y轴
                    start: 70, // 初始滚动条的位置
                    end: 100 // 滚动条结束位置
                },
                {
                    type: 'inside', // 同时在图表内部显示控制条
                    xAxisIndex: false,
                    yAxisIndex: [0]
                }
              ]
          };
          chart.setOption(option);
        })
      },
      getVendorSummary(){
        listVendorSummary(this.queryParams).then(res =>{
          let labels = [];
          if(res.data.list.length>0){
            for(let i=0;i<res.data.list.length;i++){
              labels.push(res.data.list[i].vendor_name);
            }
          }
          const chart = echarts.init(this.$refs.chart1);
          const that = this;
          const option = {
              tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                      type: 'shadow'
                  },
                  formatter: function (params) {
                      return params[0].data.extraInfo
                  }
              },
              legend: {},
              grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true
              },
              toolbox: {
                  feature: {
                      magicType: { show: true, type: ['line', 'bar'] },
                      restore: { show: true },
                      saveAsImage: { show: true }
                  }
              },
              xAxis: {
                  type: 'value',
                  boundaryGap: [0, 0.01]
              },
              yAxis: {
                  type: 'category',
                  data: labels,
              },
              series: [
                  {
                      type: 'bar',
                      barWidth: 20,
                      data: res.data.list.map(item => ({
                          value: item.orisum,
                          name: item.vendor_name,
                          extraInfo: "品种分类："+item.brand+"<br/>供应商："+item.vendor_name+"<br />金额: "+item.orisum+"万<br />金额占比："+item.mrate+"%<br />数量: "+item.qty+"<br />数量占比："+item.qrate+"%"
                      })),
                      itemStyle: {
                          color: function(params) {
                              // 颜色数组
                              const colorList = res.data.colors;
                              // 根据数据索引返回对应颜色
                              return colorList[params.dataIndex % colorList.length];
                          }
                      },
                      label: {
                          show: true, // 显示标签
                          position: 'right', // 标签位置
                          formatter: '{c}万' // 标签内容格式化为数据值
                      }
                  }
              ],
              dataZoom: [
                {
                    type: 'slider', // 这里使用slider类型
                    show: true,
                    xAxisIndex: false, // 不控制x轴
                    yAxisIndex: [0], // 控制第一个y轴
                    start: 70, // 初始滚动条的位置
                    end: 100 // 滚动条结束位置
                    // start: 20, // 初始滚动条的位置
                    // end: 40 // 滚动条结束位置
                },
                {
                    type: 'inside', // 同时在图表内部显示控制条
                    xAxisIndex: false,
                    yAxisIndex: [0]
                }
              ]
          };
          chart.setOption(option);
          chart.on('click', function(params) {
            if (params.componentType === 'series') {
              // 处理柱子点击事件
              console.log('点击了柱子:', params.name, '值:', params.value);
              console.log('选中的柱子:', params.dataIndex);
              that.queryParams.vendorName = params.name;
              chart.dispatchAction({
                type: 'downplay',
                seriesIndex: [0]
              });

              // 高亮选中的柱子
              chart.dispatchAction({
                type: 'highlight',
                seriesIndex: [0],
                dataIndex: params.dataIndex
              });

              var newData = res.data.list.map((value, index) => {
                var item = {
                  value: value.orisum,
                  itemStyle: {
                    color:res.data.colors[index],
                    opacity: 1
                  },
                };
                // 非选中的柱子设置透明度
                if (index !== params.dataIndex) {
                  item.itemStyle.opacity = 0.3;
                }
                return item;
              });

              chart.setOption({
                series: [{
                  data: newData
                }]
              });

              that.getBrandSummary();
              that.getMonthSummary();//月份同比
            }
          });
          chart.getZr().on('click', function(event) {
            if (!event.target) {
              that.queryParams.vendorName = null;
              var newData = res.data.list.map((value, index) => ({
                value: value.orisum,
                itemStyle: {
                  color:res.data.colors[index],
                  opacity: 1
                }
              }));

              chart.setOption({
                series: [{
                  data: newData
                }]
              });

              // 取消所有高亮
              chart.dispatchAction({
                type: 'downplay',
                seriesIndex: [0]
              });
              that.getBrandSummary();
              that.getMonthSummary();
            }
          });
        })
      },
      getCgDetail(){
        listCgDetail(this.queryParams).then(res =>{
          this.cgDetailList = res.data;
        })
      },
      getCgSummary(){
        listCgSummary(this.queryParams).then(res =>{
          this.summaryList = res.data;
        })
      },
      formatCurrency(value) {
        return new Intl.NumberFormat('zh-CN', {
          style: 'currency',
          currency: 'CNY',
          minimumFractionDigits: 2,
          maximumFractionDigits: 2
        }).format(value);
      },
      formatCurrency1(value) {
        return new Intl.NumberFormat('zh-CN', {
          currency: 'CNY',
          minimumFractionDigits: 0,
          maximumFractionDigits: 0
        }).format(value);
      },
      formatCurrency2(value) {
        return new Intl.NumberFormat('zh-CN', {
          currency: 'CNY',
          minimumFractionDigits: 0,
          maximumFractionDigits: 0
        }).format(value);
      },
      rowSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
            if (rowIndex === 0 || this.cgDetailList[rowIndex - 1].vendor_name !== row.vendor_name) {
                // 计算连续相同 ID 的行数
                let rowspan = 1;
                while (rowIndex + rowspan < this.cgDetailList.length && this.cgDetailList[rowIndex + rowspan].vendor_name === row.vendor_name) {
                    rowspan++;
                }
                return { rowspan, colspan: 1 };
            } else {
                return { rowspan: 0, colspan: 0 };
            }
        }
        if (columnIndex === 1) {
             if (rowIndex === 0 || this.cgDetailList[rowIndex - 1].operator_name !== row.operator_name) {
                // 计算连续相同 ID 的行数
                let rowspan = 1;
                while (rowIndex + rowspan < this.cgDetailList.length && this.cgDetailList[rowIndex + rowspan].operator_name === row.operator_name) {
                    rowspan++;
                }
                return { rowspan, colspan: 1 };
            } else {
                return { rowspan: 0, colspan: 0 };
            }
        }
        if (columnIndex === 2) {
             if (rowIndex === 0 || this.cgDetailList[rowIndex - 1].bigname !== row.bigname) {
                // 计算连续相同 ID 的行数
                let rowspan = 1;
                while (rowIndex + rowspan < this.cgDetailList.length && this.cgDetailList[rowIndex + rowspan].bigname === row.bigname) {
                    rowspan++;
                }
                return { rowspan, colspan: 1 };
            } else {
                return { rowspan: 0, colspan: 0 };
            }
        }
        if (columnIndex === 3) {
             if (rowIndex === 0 || this.cgDetailList[rowIndex - 1].xlname !== row.xlname) {
                // 计算连续相同 ID 的行数
                let rowspan = 1;
                while (rowIndex + rowspan < this.cgDetailList.length && this.cgDetailList[rowIndex + rowspan].xlname === row.xlname) {
                    rowspan++;
                }
                return { rowspan, colspan: 1 };
            } else {
                return { rowspan: 0, colspan: 0 };
            }
        }
      },
    }
}
</script>
